package com.example.myapplication.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;

import androidx.annotation.Nullable;

import com.example.myapplication.R;
import com.example.myapplication.WordApp;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

public class MusicService extends Service {

    private MediaPlayer mPlayer;

    @Override
    public void onCreate() {
        super.onCreate();
        mPlayer = new MediaPlayer();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPlayer.stop();
        mPlayer.release();
        mPlayer = null;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new MusicController();
    }

    public class MusicController extends Binder {

        private PlayListener listener;
        private boolean isReady = false;

        public boolean isPlaying() {
           if(isReady) {
               return mPlayer.isPlaying();
           }
           return false;
        }
        public void setListener(PlayListener l) {
            listener = l;
        }
        public void play() {
            if(!isReady) {
//                String path = "/storage/emulated/0/test.mp3";
//                Uri uri = Uri.fromFile(new File(path));
                mPlayer.reset();
                mPlayer = MediaPlayer.create(WordApp.AppContext, R.raw.tomorrow);
                isReady = true;

                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if(isReady && listener != null) {
                            if(mPlayer.isPlaying()) {
                                int pos = mPlayer.getCurrentPosition();
                                int duration = mPlayer.getDuration();
                                listener.notifyProgress(pos, duration);
                            }
                        }
                    }
                }, 0, 50);
            }
            mPlayer.start();
        }
        public void pause() {
            if(isReady) {
                mPlayer.pause();
            }
        }
        public void seek(int ms) {
            if(isReady) {
                mPlayer.seekTo(ms);
            }
        }
    }
}
